package com.example.demo.controller;

import com.example.demo.common.Result;
import com.example.demo.entity.Article;
import com.example.demo.entity.Category;
import com.example.demo.entity.Tag;
import com.example.demo.service.ArticleService;
import com.example.demo.service.CategoryService;
import com.example.demo.service.TagService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 博客前台控制器
 * 处理博客前台相关的HTTP请求
 */
@RestController
@RequestMapping("/api/blog")
public class BlogController {
    
    private static final Logger log = LoggerFactory.getLogger(BlogController.class);
    
    private final ArticleService articleService;
    private final CategoryService categoryService;
    private final TagService tagService;
    
    /**
     * 构造器注入
     */
    public BlogController(ArticleService articleService, CategoryService categoryService, TagService tagService) {
        this.articleService = articleService;
        this.categoryService = categoryService;
        this.tagService = tagService;
    }
    
    /**
     * 获取博客首页数据
     * @return 首页数据
     */
    @GetMapping("/home")
    public Result<Map<String, Object>> getHomeData() {
        log.info("获取博客首页数据");
        
        try {
            Map<String, Object> data = new HashMap<>();
            
            // 置顶文章
            List<Article> topArticles = articleService.getTopArticles(3);
            data.put("topArticles", topArticles);
            
            // 最新文章
            List<Article> recentArticles = articleService.getRecentArticles(10);
            data.put("recentArticles", recentArticles);
            
            // 热门文章
            List<Article> popularArticles = articleService.getPopularArticles(5);
            data.put("popularArticles", popularArticles);
            
            // 分类列表
            List<Category> categories = categoryService.getCategoriesWithArticles();
            data.put("categories", categories);
            
            // 热门标签
            List<Tag> popularTags = tagService.getPopularTags(20);
            data.put("popularTags", popularTags);
            
            return Result.success("获取首页数据成功", data);
            
        } catch (Exception e) {
            log.error("获取博客首页数据失败：", e);
            return Result.error("获取首页数据失败");
        }
    }
    
    /**
     * 分页获取文章列表
     * @param page 页码
     * @param size 每页大小
     * @param categoryId 分类ID
     * @param keyword 搜索关键词
     * @return 文章列表
     */
    @GetMapping("/articles")
    public Result<ArticleService.PageResult<Article>> getArticleList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Long categoryId,
            @RequestParam(required = false) String keyword) {
        
        log.info("分页获取文章列表，页码：{}，大小：{}，分类：{}，关键词：{}", page, size, categoryId, keyword);
        
        try {
            ArticleService.PageResult<Article> pageResult = articleService.getArticleList(
                page, size, categoryId, Article.Status.PUBLISHED, keyword);
            
            return Result.success("获取文章列表成功", pageResult);
            
        } catch (Exception e) {
            log.error("获取文章列表失败：", e);
            return Result.error("获取文章列表失败");
        }
    }
    
    /**
     * 获取文章详情
     * @param id 文章ID
     * @return 文章详情
     */
    @GetMapping("/articles/{id}")
    public Result<Article> getArticleDetail(@PathVariable Long id) {
        log.info("获取文章详情，ID：{}", id);
        
        try {
            Article article = articleService.getArticleById(id, true); // 增加阅读量
            
            // 只返回已发布的文章
            if (article.getStatus() != Article.Status.PUBLISHED) {
                return Result.error(404, "文章不存在或未发布");
            }
            
            return Result.success("获取文章详情成功", article);
            
        } catch (Exception e) {
            log.error("获取文章详情失败，ID：{}", id, e);
            return Result.error("获取文章详情失败");
        }
    }
    
    /**
     * 根据标签获取文章列表
     * @param tagId 标签ID
     * @param page 页码
     * @param size 每页大小
     * @return 文章列表
     */
    @GetMapping("/articles/tag/{tagId}")
    public Result<ArticleService.PageResult<Article>> getArticlesByTag(
            @PathVariable Long tagId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        log.info("根据标签获取文章列表，标签ID：{}，页码：{}，大小：{}", tagId, page, size);
        
        try {
            ArticleService.PageResult<Article> pageResult = articleService.getArticlesByTag(tagId, page, size);
            return Result.success("获取文章列表成功", pageResult);
            
        } catch (Exception e) {
            log.error("根据标签获取文章列表失败：", e);
            return Result.error("获取文章列表失败");
        }
    }
    
    /**
     * 文章点赞
     * @param id 文章ID
     * @return 操作结果
     */
    @PostMapping("/articles/{id}/like")
    public Result<String> likeArticle(@PathVariable Long id) {
        log.info("文章点赞，ID：{}", id);
        
        try {
            boolean success = articleService.likeArticle(id);
            if (success) {
                return Result.success("点赞成功");
            } else {
                return Result.error("点赞失败");
            }
            
        } catch (Exception e) {
            log.error("文章点赞失败，ID：{}", id, e);
            return Result.error("点赞失败");
        }
    }
    
    /**
     * 获取所有分类
     * @return 分类列表
     */
    @GetMapping("/categories")
    public Result<List<Category>> getAllCategories() {
        try {
            List<Category> categories = categoryService.getAllCategories();
            return Result.success("获取分类列表成功", categories);
        } catch (Exception e) {
            log.error("获取分类列表失败：", e);
            return Result.error("获取分类列表失败");
        }
    }
    
    /**
     * 获取所有标签
     * @return 标签列表
     */
    @GetMapping("/tags")
    public Result<List<Tag>> getAllTags() {
        try {
            List<Tag> tags = tagService.getAllTags();
            return Result.success("获取标签列表成功", tags);
        } catch (Exception e) {
            log.error("获取标签列表失败：", e);
            return Result.error("获取标签列表失败");
        }
    }
    
    /**
     * 获取热门标签
     * @param limit 数量限制
     * @return 热门标签列表
     */
    @GetMapping("/tags/popular")
    public Result<List<Tag>> getPopularTags(@RequestParam(defaultValue = "20") int limit) {
        try {
            List<Tag> tags = tagService.getPopularTags(limit);
            return Result.success("获取热门标签成功", tags);
        } catch (Exception e) {
            log.error("获取热门标签失败：", e);
            return Result.error("获取热门标签失败");
        }
    }
    
    /**
     * 高级搜索文章
     */
    @GetMapping("/search")
    public Result<Map<String, Object>> searchArticles(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Long categoryId,
            @RequestParam(required = false) String tags,
            @RequestParam(defaultValue = "latest") String sortBy,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        log.info("高级搜索文章 - 关键词：{}，分类：{}，标签：{}，排序：{}", keyword, categoryId, tags, sortBy);
        
        try {
            // 使用现有的文章列表方法进行搜索
            ArticleService.PageResult<Article> pageResult = articleService.getArticleList(
                page, size, categoryId, Article.Status.PUBLISHED, keyword);
            
            // 如果有标签筛选，进一步过滤结果
            List<Article> articles = pageResult.getRecords();
            if (tags != null && !tags.trim().isEmpty()) {
                String[] tagNames = tags.split(",");
                articles = articles.stream()
                    .filter(article -> {
                        List<Tag> articleTags = articleService.getArticleTags(article.getId());
                        return articleTags.stream()
                            .anyMatch(tag -> java.util.Arrays.asList(tagNames).contains(tag.getName()));
                    })
                    .collect(java.util.stream.Collectors.toList());
            }
            
            // 为每篇文章加载标签
            for (Article article : articles) {
                List<Tag> articleTags = articleService.getArticleTags(article.getId());
                article.setTags(articleTags);
            }
            
            Map<String, Object> data = new HashMap<>();
            data.put("articles", articles);
            data.put("total", pageResult.getTotal());
            data.put("page", pageResult.getPage());
            data.put("size", pageResult.getSize());
            data.put("totalPages", pageResult.getPages());
            data.put("keyword", keyword);
            data.put("categoryId", categoryId);
            data.put("tags", tags);
            data.put("sortBy", sortBy);
            
            return Result.success("搜索完成", data);
            
        } catch (Exception e) {
            log.error("搜索文章失败", e);
            return Result.error("搜索失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取搜索建议
     */
    @GetMapping("/search/suggestions")
    public Result<Map<String, Object>> getSearchSuggestions(@RequestParam String query) {
        log.info("获取搜索建议，查询：{}", query);
        
        try {
            // 搜索匹配的文章（简化实现）
            ArticleService.PageResult<Article> articles = articleService.getArticleList(1, 5, null, Article.Status.PUBLISHED, query);
            List<String> suggestions = articles.getRecords().stream()
                    .map(Article::getTitle)
                    .collect(java.util.stream.Collectors.toList());
            
            // 搜索匹配的分类
            List<Category> categories = categoryService.getAllCategories().stream()
                    .filter(cat -> cat.getName().toLowerCase().contains(query.toLowerCase()))
                    .limit(3)
                    .collect(java.util.stream.Collectors.toList());
            List<String> categoryNames = categories.stream()
                    .map(Category::getName)
                    .collect(java.util.stream.Collectors.toList());
            
            // 搜索匹配的标签
            List<Tag> tags = tagService.getAllTags().stream()
                    .filter(tag -> tag.getName().toLowerCase().contains(query.toLowerCase()))
                    .limit(5)
                    .collect(java.util.stream.Collectors.toList());
            List<String> tagNames = tags.stream()
                    .map(Tag::getName)
                    .collect(java.util.stream.Collectors.toList());
            
            Map<String, Object> data = new HashMap<>();
            data.put("articles", suggestions);
            data.put("categories", categoryNames);
            data.put("tags", tagNames);
            
            return Result.success("获取搜索建议成功", data);
            
        } catch (Exception e) {
            log.error("获取搜索建议失败", e);
            return Result.error("获取搜索建议失败：" + e.getMessage());
        }
    }
}
